<template>
  <div class="createEdit-container">
    <div class="app-title-container title-position">
      <modules-title :title-name="titleName">
        <template slot="btn">
          <el-button
            plain
            @click="goBack"
          >返回</el-button>
          <el-button
            type="primary"
            :disabled="isSave"
            @click="saveForm"
          >保存</el-button>
          <el-button
            v-hasPermi="{ v: ['quality:all'], isF: true }"
            type="primary"
            @click="submitForm"
          >提交审批</el-button>
        </template>
      </modules-title>
    </div>
    <div class="app-main-container main-content-container">
      <div class="base-info-container">
        <!-- <item-title title="基础信息" /> -->
        <el-form
          ref="elForm"
          :model="tableFormData"
          :rules="rules"
          size="small"
          label-width="150px"
        >
          <el-row
            :gutter="40"
            class="form-row01"
          >
            <el-col :span="12">
              <el-form-item
                label="文件名称："
                prop="quality_standard_name"
              >
                <el-input
                  v-model="tableFormData.quality_standard_name"
                  placeholder="请输入文件名称"
                  clearable
                  :style="{ width: '100%' }"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="文件编号："
                prop="quality_standard_no"
              >
                <el-input
                  v-model="tableFormData.quality_standard_no"
                  :disabled="types!=='create'"
                  placeholder="请输入文件编号"
                  clearable
                  :style="{ width: '100%' }"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="40"
            class="form-row01"
          >
            <el-col :span="12">
              <el-form-item
                label="文件类型："
                prop="quality_type_id"
              >
                <el-select
                  v-model="tableFormData.quality_type_id"
                  placeholder="请选择文件类型"
                  :style="{ width: '100%' }"
                  @change="qualityTypeChange"
                >
                  <el-option
                    v-for="(item, index) in qualityTypeOptions"
                    :key="item.id"
                    :label="item.dict_val"
                    :value="item.id"
                    :disabled="item.disabled"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="版本号："
                prop="version"
              >
                <el-input
                  v-model="tableFormData.version"
                  class="version"
                  :disabled="types!=='change'&&types!=='create'"
                  placeholder="请输入文件版本号"
                  clearable
                  :style="{ width: '100%' }"
                >
                  <template slot="prepend">V</template>
                  <!-- <template #suffix>
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="版本号前缀固定为V，无需输入"
                      placement="left-end"
                    >
                      <i class="iconfont el-icon-question" />
                    </el-tooltip>
                  </template> -->
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="40"
            class="form-row01"
          >
            <el-col :span="12">
              <el-form-item
                label="文件来源："
                prop="quality_source_id"
              >
                <el-select
                  v-model="tableFormData.quality_source_id"
                  placeholder="请选择文件来源"
                  :style="{ width: '100%' }"
                  @change="qualitySourceChange"
                >
                  <el-option
                    v-for="(item, index) in qualitySourceOptions"
                    :key="item.id"
                    :label="item.dict_val"
                    :value="item.id"
                    :disabled="item.disabled"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="适用范围："
                prop="sample_type_list"
              >
                <el-select
                  v-model="tableFormData.sample_type_list"
                  multiple
                  collapse-tags
                  value-key="sample_type_key"
                  placeholder="请选择适用范围"
                  :style="{ width: '100%' }"
                  @change="sampleTypeChange"
                >
                  <el-option
                    v-for="(item, index) in sampleTypeOptions"
                    :key="item.id"
                    :label="item.dict_val"
                    :value="{'sample_type_key': item.dict_key, 'sample_type_value': item.dict_val}"
                    :disabled="item.disabled"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="40"
            class="form-row01"
          >
            <el-col :span="12">
              <el-form-item
                label="项目名称："
                prop="project_id"
              >
                <el-select
                  v-model="tableFormData.project_id"
                  placeholder="请选择项目"
                  clearable
                  filterable
                  :style="{ width: '100%' }"
                  @change="projectChange"
                >
                  <el-option
                    v-for="item in projectOptions"
                    :key="item.id"
                    :label="item.project_name"
                    :value="item.id"
                    :disabled="item.disabled"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col
              v-if="types==='change'"
              :span="12"
            >
              <el-form-item
                label="变更原因："
                :prop="types==='change'?'change_description':'normal'"
              >
                <el-input
                  v-model="tableFormData.change_description"
                  placeholder="请输入变更原因"
                  clearable
                  :style="{ width: '100%' }"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="检验依据文件附件："
                prop="file"
                :show-message="false"
              >
                <upload-select
                  ref="upload"
                  :limit="1"
                  :edit-list="tableFormData.file || []"
                  :project-data="{project_id: 'quality',validation: 1}"
                  @uploadSuccess="uploadSuccess"
                  @deleteSuccess="deleteSuccess"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import {
  createQualitySource,
  qualitySourceDetail,
  qualitySourceEdit,
  changeQuality,
  projectList,
  submitAudit
} from '@/api/qualitySource'
export default {
  components: {},
  data() {
    var filePass = (rule, value, callback) => {
      const fileList = this.$refs.upload.emitFileList() || []
      const newList = this.$refs.upload.emitNewFileList() || []
      if (fileList.length !== 0 || newList.length !== 0) {
        callback()
      } else {
        this.$message.error('请上传文件附件')
      }
    }
    return {
      types: '', // 判断编辑与变更
      titleName: '创建检验依据',
      isSave: false,
      isInput: false,
      qualitySourceId: '',
      tableFormData: {
        quality_standard_no: '',
        version: '',
        quality_standard_name: '',
        quality_type_id: '',
        quality_type_name: '',
        quality_source_id: '',
        quality_source_name: '',
        project_id: '',
        project_name: '',
        sample_type_key: '',
        sample_type_value: '',
        sample_type_list: [],
        quality_standard_status: 1,
        project_list: [],
        file: [],
        change_description: ''
      },
      formRules: {
        check_out_project_name: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }
        ],
        check_out_method: [
          {
            required: true,
            message: '请输入检验方法',
            trigger: 'blur'
          }
        ],
        check_out_standard: [
          {
            required: true,
            message: '请输入检验标准',
            trigger: 'blur'
          }
        ]
      },
      rules: {
        quality_standard_name: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        quality_standard_no: [
          {
            required: true,
            message: '请输入编号',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        version: [
          {
            required: true,
            message: '请输入版本号',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        change_description: [
          {
            required: true,
            message: '请输入变更原因',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        quality_type_id: [
          {
            required: true,
            message: '请选择类型',
            trigger: 'change'
          }
        ],
        quality_source_id: [
          {
            required: true,
            message: '请选择文件来源',
            trigger: 'change'
          }
        ],
        project_id: [
          {
            required: true,
            message: '请选择项目',
            trigger: 'change'
          }
        ],
        sample_type_list: [
          {
            required: true,
            type: 'array',
            message: '请选择适用范围',
            trigger: 'change'
          }
        ],
        file: [
          {
            type: 'array',
            required: true,
            validator: filePass,
            trigger: 'change'
          }
        ],
        normal: []
      },
      qualitySourceOptions: [
        {
          label: '自研',
          value: '1'
        },
        {
          label: '委托',
          value: '2'
        }
      ],
      qualityTypeOptions: [
        {
          label: '仿制药',
          value: '1'
        },
        {
          label: '创新药',
          value: '2'
        },
        {
          label: '中药',
          value: '3'
        }
      ],
      projectOptions: [],
      sampleTypeOptions: []
    }
  },
  computed: {},
  watch: {},
  created() {
    this.qualitySourceId = this.$route.query.qualitySourceId || ''
    this.types = this.$route.query.types || ''
    if (this.qualitySourceId) {
      if (this.types === 'edit') {
        this.titleName = '编辑检验依据'
      } else if (this.types === 'change') {
        this.titleName = '变更检验依据'
      }
      this.getQualitySourceDetail(this.qualitySourceId)
    } else {
      this.titleName = '创建检验依据'
    }
    this.getProjectList({ project_status: [4, 5, 6, 7, 8] })
    this.getSysAllDic()
  },
  mounted() {},
  methods: {
    goBack() {
      this.$router.back()
    },
    getSysAllDic() {
      let allDic = this.$store.getters.sysDic()
      if (!allDic) {
        this.$store.dispatch('sys/getSysAllDic').then((data) => {
          allDic = data
        })
      }
      console.log(allDic)
      this.qualityTypeOptions = allDic['quality_type']
      this.qualitySourceOptions = allDic['quality_source']
      this.sampleTypeOptions = allDic['sample_type']
    },
    getProjectList(datas) {
      projectList(datas).then((res) => {
        if (res.code === 200) {
          this.projectOptions = res.data
        }
      })
    },
    deleteSuccess() {
      // this.tableFormData.file = this.$refs.upload.emitFileList()
    },
    uploadSuccess() {
      // this.tableFormData.file = this.$refs.upload.emitFileList()
    },
    // 录入文件
    inputContent() {
      this.isInput = true
    },
    uploadContent() {
      this.isInput = false
      this.tableFormData.project_list = []
    },
    // 文件来源选择改变
    qualitySourceChange(val) {
      const obj = this.qualitySourceOptions.find((itm) => {
        return itm.id === val
      })
      this.tableFormData.quality_source_name = obj.dict_val
      console.log(val, this.tableFormData)
    },
    // 类型改变
    qualityTypeChange(val) {
      const obj = this.qualityTypeOptions.find((itm) => {
        return itm.id === val
      })
      this.tableFormData.quality_type_name = obj.dict_val
      console.log(val, this.tableFormData)
    },
    projectChange(val) {
      const obj = this.projectOptions.find((itm) => {
        return itm.id === val
      })
      this.tableFormData.project_name = obj ? obj.project_name : ''
    },
    // 样品类型选择改变
    sampleTypeChange(val) {
      // const obj = this.sampleTypeOptions.find((itm) => {
      //   return itm.id === val
      // })
      // this.tableFormData.sample_type_value = obj.dict_val
      console.log(val, this.tableFormData)
    },
    // 获取文件详情
    getQualitySourceDetail(id) {
      const datas = { id: id }
      qualitySourceDetail(datas).then((res) => {
        if (res.code === 200) {
          var datas = res.data
          datas.change_description = ''
          // 变更不需要带原来的附件
          if (this.types === 'change') {
            datas.file = []
          }
          this.tableFormData = datas
          if (this.tableFormData.file && this.tableFormData.file.length) {
            this.isInput = false
          }
          if (
            this.tableFormData.project_list &&
            this.tableFormData.project_list.length
          ) {
            this.isInput = true
          }
        }
      })
    },
    formRulesOperation(callback) {
      let arrs = []
      const p1 = new Promise((resolve, reject) => {
        this.$refs['elForm'].validate((valid) => {
          if (valid) resolve()
        })
      })
      if (this.isInput) {
        const p2 = new Promise((resolve, reject) => {
          this.$refs['tableForm'].validate((valid) => {
            if (valid) resolve()
          })
        })
        arrs = [p1, p2]
      } else {
        arrs = [p1]
      }

      return Promise.all(arrs)
    },
    // 返回之后刷新列表
    refreshBack() {
      this.$route.params.refresh = true
      this.$router.back()
    },
    // 直接提交---需要调保存接口（此处分创建和更新），成功后调提交审核接口
    async submitManage() {
      let createRes = null
      let qid = ''
      if (this.qualitySourceId) {
        qid = this.qualitySourceId
        if (this.types === 'edit') {
          createRes = await qualitySourceEdit(
            { id: this.qualitySourceId },
            this.tableFormData
          )
        } else if (this.types === 'change') {
          createRes = await changeQuality(
            { id: this.qualitySourceId },
            this.tableFormData
          )
        }
      } else {
        createRes = await createQualitySource(this.tableFormData)
      }
      if (createRes.code === 200) {
        if (this.types === 'create' || this.types === 'edit') {
          qid = this.qualitySourceId || createRes.data.id
        } else if (this.types === 'change') {
          qid = createRes.data.id
        }
      } else {
        this.$message({
          type: 'error',
          message: createRes.msg,
          duration: 1500
        })
        return
      }
      const subAudit = await submitAudit({ id: qid })
      if (subAudit.code === 200) {
        this.refreshBack()
      } else {
        this.$message({
          type: 'error',
          message: subAudit.msg,
          duration: 1500
        })
      }
    },
    submitForm() {
      const that = this
      this.formRulesOperation().then(() => {
        console.log('验证通过')
        that.$refs.upload
          .saveFile()
          .then((dataList) => {
            that.tableFormData.file = dataList[0]
            if (that.tableFormData.file && that.tableFormData.file.length) {
              that.submitManage()
            } else {
              that.$message.error('请上传文件附件')
            }
          })
          .catch((err) => {
            console.log(err)
            that.$message.error(err)
          })
      })
    },
    createQualitySourceOperation() {
      createQualitySource(this.tableFormData).then((res) => {
        if (res.code === 200) {
          this.qualitySourceId = res.data.id
          this.refreshBack()
        } else {
          this.isSave = false
          this.$message({
            type: 'error',
            message: res.msg,
            duration: 1500
          })
        }
      })
    },
    updateQualitySource() {
      const par = { id: this.qualitySourceId }
      qualitySourceEdit(par, this.tableFormData).then((res) => {
        if (res.code === 200) {
          this.refreshBack()
        } else {
          this.isSave = false
          this.$message({
            type: 'error',
            message: res.msg,
            duration: 1500
          })
        }
      })
    },
    // 变更保存
    changeSave() {
      changeQuality({ id: this.qualitySourceId }, this.tableFormData).then(
        (res) => {
          if (res.code === 200) {
            this.$route.params.refresh = true
            this.isSave = false
            this.$message.success('变更保存成功')
          } else {
            this.isSave = false
            this.$message.error(res.msg)
          }
        }
      )
    },
    // 保存草稿
    saveForm() {
      const that = this
      this.tableFormData.quality_standard_status = 1
      this.formRulesOperation().then(() => {
        console.log('验证通过')
        that.$refs.upload
          .saveFile()
          .then((dataList) => {
            that.isSave = true
            that.tableFormData.file = dataList[0]
            if (that.tableFormData.file && that.tableFormData.file.length) {
              if (that.qualitySourceId) {
                if (that.types === 'create' || that.types === 'edit') {
                  that.updateQualitySource()
                } else if (this.types === 'change') {
                  that.changeSave()
                }
              } else {
                that.createQualitySourceOperation()
              }
            } else {
              that.$message.error('请上传文件附件')
              that.isSave = false
            }
          })
          .catch((err) => {
            this.isSave = false
            console.log(err)
          })
      })
    },
    deleteItem(index) {
      this.tableFormData.project_list.splice(index, 1)
    },
    addItem() {
      const itm = {
        check_out_project_id: '',
        check_out_project_name: '',
        check_out_method: '',
        check_out_standard: ''
      }
      this.tableFormData.project_list.push(itm)
    },
    nameHandleSelect(val, index) {
      console.log(val, index)
    },
    commonCreateFilter(queryString) {
      return (restaurant) => {
        return restaurant.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      }
    },
    // 用药频率输入联想--开始
    nameQuerySearch(queryString, cb) {
      var restaurants = this.remindData.eat_rate
      var results = queryString
        ? restaurants.filter(this.commonCreateFilter(queryString))
        : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
.createEdit-container {
  padding-top: 110px;
}
.files-container {
  .btn-tip {
    font-size: $font-size-main;
    color: $font-color-info;
  }
  .btn {
    font-size: $font-size-main;
    color: $main-color;
    &:hover {
      cursor: pointer;
    }
  }
}
.base-info-container {
  .el-form {
    ::v-deep .version {
      .el-input__suffix {
        top: 8px;
      }
    }
  }
}

.form-table {
  &.el-table--enable-row-hover {
    ::v-deep .el-table__body tr:hover > td {
      background-color: transparent;
    }
  }
  ::v-deep .el-table__body {
    .el-table__row {
      td {
        padding: 5px !important;
        .cell {
          padding: 0px;
        }
        .el-form-item {
          margin-bottom: 0px;
          .el-input__inner {
            border-width: 0px;
            border-radius: 0px;
          }

          &.is-error {
            .el-input__inner {
              border-width: 1px;
            }
          }
        }
      }
    }
  }
}
</style>
